package com.usian.article.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.apis.article.AuthorControllerApi;
import com.usian.article.service.impl.AuthorServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/author")
public class AuthorController implements AuthorControllerApi {
   @Autowired
   private AuthorServiceImpl authorService;

    /**
     * 按照用户id查询作者信息
     * @param id
     * @return
     */
    @Override
    @GetMapping("/findByUserId/{id}")
    public ApAuthor findByUserId(@PathVariable Integer id) {
        List<ApAuthor> list = authorService.list(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getUserId, id));
        if(list!=null &&!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }

    /**
     * 保存作者
     * @param apAuthor
     * @return
     */
    @Override
    @PostMapping("/save")
    public ResponseResult save(@RequestBody ApAuthor apAuthor) {
        apAuthor.setCreatedTime(new Date());
        authorService.save(apAuthor);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据名称查询作者
     * @param name
     * @return
     */
    @GetMapping("findByName/{name}")
    @Override
    public ApAuthor findByName(@PathVariable String name) {
        ApAuthor apAuthor = (ApAuthor) authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, name));
        return apAuthor;
    }

    /**
     * 根据id查询作者
     * @param id
     * @return
     */
    @GetMapping("/one/{id}")
    @Override
    public ApAuthor findById(@PathVariable("id") Integer id) {
        List<ApAuthor> list = authorService.list(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getId, id));
        if(list!=null &&!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }
}
